package com.borderbears.backend.util;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 
 * @author bask
 */
public class Config {
	private final Logger log = Logger.getLogger(getClass().getName());

	private static Config instance;
	private File file;
	private Properties props;

	private Config() {}
	
	public int get(final String key, final int defaultValue) {
		try {
			final int re = Integer.parseInt(get(key, Integer.toString(defaultValue)));
			return re;
		} catch (final NumberFormatException e) {
			log.warning("Error while parsing integer value for key: "+key+" using default instead.");
		}
		return defaultValue;
	}

	public boolean get(final String key, final boolean defaultValue) {
		return Boolean.parseBoolean(get(key, Boolean.toString(defaultValue)));
	}

	public void set(final String key, final boolean value) {
		set(key, Boolean.toString(value));
	}

	public void set(final String key, final int value) {
		set(key, Integer.toString(value));
	}

	public String get(final String key, final String defaultValue) {
		final String v = props.getProperty(key);
		if (null == v) {
			set(key, defaultValue);
			return defaultValue;
		}
		return v;
	}

	public void set(final String key, final String value) {
		try {
			props.setProperty(key, value);
			props.store(new FileOutputStream(file), "Config");
		} catch (final IOException ex) {
			Logger.getLogger(Config.class.getName())
					.log(Level.SEVERE, null, ex);
		}
	}

	public void setFile(final String filename) {
		file = new File(filename);
		props = new Properties();
		if (!file.exists()) {
			log.warning("Config file does not exist, creating new one: "+filename);
			try {
				props.store(new FileOutputStream(file), "Config");
			} catch (final FileNotFoundException e) {
				e.printStackTrace();
			} catch (final IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				props.load(new FileInputStream(file));
			} catch (final IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static Config getConfig() {
		if (null == instance) {
			instance = new Config();
		}
		return instance;
	}

}
